use lib "./";

use POSIX qw(strftime);
use File;
use Compress;

$GIT_DIR = $ARGV[0];
$GIT_DOMAIN = $ARGV[1];
$PASTE_DIR = $ARGV[2];
$IMAGE_MAGICK_DIR = $ARGV[3];
print "0 = $GIT_DIR \n 1 = $GIT_DOMAIN \n 2 = $PASTE_DIR \n 3 = $IMAGE_MAGICK_DIR \n";

$ONE_MB = 1024 * 1024;

$picUrl = execute();

system("echo '$picUrl' | pbcopy");

sub execute{
    
    my $fileInfo = "none";
    if(isPath()){
        $fileInfo = handleClipboard();
    }

    my $fileName = getFileName($fileInfo);
    my $target = getFile($GIT_DIR, $fileName);
    my $newFileName = copy($fileInfo, $target, $fileName); 

    executeGit();
    
    my $picUrl = getPicUrl($newFileName);
    return $picUrl;
}

# return 1 if the first element is a path in clipboard, else return 0. 
sub isPath(){
    my $result = `pbpaste`;
    if($result) {
        return 1;
    } else {
        return 0;
    }
}

sub getPicUrl{
    my $fileName = @_[0];
    my $today = today();
    return "![]($GIT_DOMAIN/$today/$fileName)";
}

sub executeGit{
    system("git --git-dir='$GIT_DIR/.git' --work-tree='$GIT_DIR' add .");
    system("git --git-dir='$GIT_DIR/.git' --work-tree='$GIT_DIR' commit -m 'pic'");
    system("git --git-dir='$GIT_DIR/.git' --work-tree='$GIT_DIR' push");
}

sub getFileName{
    
    my $path = @_[0];
    if($path eq "none"){
        my $r = 10000;
        my $epoc = time();
        my $num = int(rand($r)) + $r;
        return $epoc . "serpmelon" . $num . ".png";
    } else {
        my @arr = split /\//, $path;
        return @arr[-1];
    }
}

sub copy{
    my $source = @_[0];
    my $target = @_[1];
    my $filename = @_[2];
    if($source eq "none"){
        system("$PASTE_DIR/pngpaste $target"); 
    } else {
        system("cp $source $target");
    }

    my $fileObj = File->new($target);
    if($fileObj->size > $ONE_MB && $fileObj->suffix eq 'png') {

        my $config = {imageMagickDir => $IMAGE_MAGICK_DIR};
        my $compressObj = Compress->new($config);
        my $comRe =$compressObj->png2jpg($target);
        $filename = $comRe->{filename};
        if($comRe->{size} > $ONE_MB) {
            print "need another op \n";
        }
    }
    
    $filename;
}

sub handleClipboard{
    # use `` to execute shell command and get the return value;
    my $result = `pbpaste`;
    return $result;
}

# get file
sub getFile{
	my $dic = @_[0];
    my $fileName = @_[1];
    my $today = today();
    my $file = $dic ."/$today/";
    # create file if not exists
    unless(-e $file) {
    	mkdirRecur($file);
    }

	return $file . $fileName;
}

# like 20220102
sub today{
 return strftime "%Y%m%d", localtime;
}

sub mkdirRecur{
    my $file = $_[0];
	my @path = split /\//, $file;
	my $max = $#path;
	foreach (0..$max) {
		my $f = join "\/", @path[0..$_];
		unless(-e $f){
		    mkdir $f;
		}
	}
}


